package com.saoft.dbinfo.updates;

import com.saoft.dbinfo.po.TableField;
import com.saoft.dbinfo.po.TableInfo;

public class MysqlUpdate extends AbstractDbUpdate {
    @Override
    public String createTable(TableInfo tableInfo) {

        StringBuffer buffer = new StringBuffer();
        buffer.append(String.format("CREATE TABLE `%s` (", tableInfo.getName()));

        String pk = "";
        for (TableField tableField : tableInfo.getFields()) {
            if (tableField.isKeyIdentityFlag()) {
                buffer.append(String.format("`%s` %s NOT NULL AUTO_INCREMENT COMMENT 'ID',", tableField.getName(), tableField.getType()));
                pk = "  PRIMARY KEY (`"+tableField.getName()+"`)";
            }else{
                buffer.append(String.format(" `%s` ", tableField.getName()));
                buffer.append(tableField.getType());
                buffer.append(" ");
                if(tableField.isAbleNull()){
                    buffer.append(" NOT NULL ");
                }
                if (tableField.getComment() != null) {

                    buffer.append(String.format(" COMMENT '%s' ",tableField.getComment()));
                }
                buffer.append(",");
            }
        }
        buffer.append(pk);
        buffer.append(String.format(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='%s'", tableInfo.getComment()));

//        String sql = "CREATE TABLE `admin` (\n" +
//                "  `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
//                "  `number` varchar(20) NOT NULL COMMENT '登录编号',\n" +
//                "  PRIMARY KEY (`id`)\n" +
//                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='系统管理员';";

        return buffer.toString();
    }
}
